import moviepy.editor as mp
import pygame as pg

from moviepy.video.io.preview import preview, imdisplay

'''
pygame.event.MOUSEMOTION鼠标移动事件

    event.pos 相对于窗口左上角，鼠标的当前坐标值(x,y)
    event.rel 鼠标相对运动距离(X,Y)，相对于上次事件
    event.buttons 鼠标按钮初始状态(0,0,0)，分别对应(左键,滑轮,右键)，移动过程中点击那个键，相应位置变会为1

pygame.event.MOUSEBUTTONUP鼠标键释放事件

    event.pos 相对于窗口左上角，鼠标的当前坐标值(x,y)
    event.button 鼠标释放键编号（整数）左键为1，按下滚动轮2、右键为3

pygame.event.MOUSEBUTTONDOWN 鼠标键按下事件

    event.pos 相对于窗口左上角，鼠标的当前坐标值(x,y)
    event.button 鼠标按下键编号（整数），左键为1，按下滚动轮2、右键为3，向前滚动滑轮4、向后滚动滑轮5

'''


def preview_pygame_clip(video, times=1, base_fps=10):
    BASE_FPS = base_fps
    wait_flag = False
    pg.init()
    screen = pg.display.set_mode((800, 500))
    pg.display.set_caption('视频预览')
    video = video.resize((800, 500))

    clock = pg.time.Clock()
    # 将原视频改为10fps的帧
    frames = video.iter_frames(fps=BASE_FPS)
    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit()
            if event.type == pg.KEYUP:
                if event.key == pg.K_SPACE:
                    wait_flag = not wait_flag
            if event.type == pg.MOUSEBUTTONUP:
                if event.button == 1:
                    wait_flag = not wait_flag

        if not wait_flag:
            try:
                imdisplay(next(frames), screen=screen)
            except:
                break

        clock.tick(times * BASE_FPS)
        pg.display.update()

    pg.quit()


def main():
    video = mp.VideoFileClip('../素材demo/小电影.mp4')
    # preview_sp()
    # preview_iter_frames(video=video)
    preview_pygame_click(video=video)


if __name__ == '__main__':
    main()
